package com.hongchen.wechat.service;

import com.hongchen.model.ActGame;
import com.hongchen.model.ActGamePrize;
import com.hongchen.model.ActPrize;
import com.hongchen.model.ActUser;
import com.realdtech.base.ServiceSupport;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by 3426624897@qq.com on 2018/2/8 0008.
 */
public class RichService extends ServiceSupport{

    private final ActUser dao = new ActUser().dao();
    private final ActGame gameDao = new ActGame().dao();
    private final ActPrize prizeDao = new ActPrize().dao();//奖品
    private final ActGamePrize priGameDao = new ActGamePrize().dao();//中间表


    /*根据用户的openid查询数据库中陪你晒郑州集卡情况*/
    public List<ActGamePrize> coolect(String openid) {
        return priGameDao.find("SELECT prize_id from " + ActUser.TABLE_NAME + "  auser LEFT JOIN " + ActGame.TABLE_NAME + " agame " +
                "ON auser.id=agame.act_user_id LEFT JOIN " + ActGamePrize.TABLE_NAME + " agprize ON agame.id=agprize.game_id " +
                "LEFT JOIN " + ActPrize.TABLE_NAME +
                " aprize ON agprize.prize_id=aprize.id WHERE agprize.prize_id in(1,2,3,4,5) AND is_recive=0 AND wechat_openid=?", openid);
    }

    /*兑换陪你晒郑州的时候把是否领奖的转改修改为1*/
    public void updateIsRecive(String openid) {
        priGameDao.getDb().update("UPDATE " + ActGamePrize.TABLE_NAME + " set is_recive=1 where prize_id in(1,2,3,4,5) AND is_recive=0 and game_id=(SELECT  id from "
                + ActGame.TABLE_NAME + " where act_user_id =(SELECT id from " + ActUser.TABLE_NAME + " where wechat_openid=?))", openid);
    }

    /*userid*/
    public void lessSieveChance(Long userid) {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set sieve_chance=(sieve_chance-1) where act_user_id=?", userid);
    }

    /*当当前步数加掷骰子步数大于92的时候*/
    public void lessSteapo(int dicenum, Long userid) {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set now_step=(now_step-92+?) where act_user_id=?", dicenum, userid);
    }

    public void lessSteapo( Long userid) {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set now_step=(1) where act_user_id=?",  userid);
    }

    public void updateSteap(int dicenum, Long userid) {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set now_step=(now_step + ? ) where act_user_id=?", dicenum, userid);
    }

    public ActUser findUser(Long userid) {
        ActUser actUser = dao.findFirst("select * from " + ActUser.TABLE_NAME + " where id=?", userid);
        return actUser;
    }

    //使用用户的openid在数据库中查询用户是否已经存在
    public ActUser findByOpenid(String openid) {
        ActUser actUser = dao.findFirst("select * from " + ActUser.TABLE_NAME + " where wechat_openid=?", openid);
        return actUser;
    }

    //使用用户id作为act_user_id在游戏表中查询用户的信息
    public ActGame finds(Long userid) {
        ActGame actGame = gameDao.findFirst("select * from " + ActGame.TABLE_NAME + " where act_user_id=?", userid);
        return actGame;
    }

    /*增加用户掷骰子机会加一*/
    public void updateSieveChance(Long userid) {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set sieve_chance=(sieve_chance+1) where act_user_id=?", userid);
    }

    /*增加用户掷骰子机会加二*/
    public void updateSieveChanceTwo(Long userid) {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set sieve_chance=(sieve_chance+2) where act_user_id=?", userid);
    }

    /*增加用户掷骰子机会加4*/
    public void updateSieveChanceFour(Long userid) {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set sieve_chance=(sieve_chance+4) where act_user_id=?", userid);
    }

    /*增加用户掷骰子机会加6*/
    public void updateSieveChanceSix(Long userid) {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set sieve_chance=(sieve_chance+6) where act_user_id=?", userid);
    }

    /*为找弟字过了60关的人查询到他的奖品编号，通过openid*/
    public ActGamePrize findPrize(String openid) {
        ActGamePrize actGamePrize = priGameDao.findFirst("SELECT *from " + ActGamePrize.TABLE_NAME + " where game_id=" +
                "(SELECT id from " + ActGame.TABLE_NAME + " where act_user_id=(SELECT id from " + ActUser.TABLE_NAME + " where wechat_openid=?))" +
                " ORDER BY award_time DESC", openid);
        return actGamePrize;
    }

    /*查询用户上次游戏时间距离现在的天数,不满24小时则为0*/
    public Long lastDays(Long userid) {
        Long num = gameDao.getDb().queryLong("select timestampdiff(day,ag.now_time,now()) from " + ActGame.TABLE_NAME + "  ag where ag.act_user_id=?", userid);
        return num;
    }

    /*每天晚上0点的时候把所有人的抽奖机会恢复成5，
  * 重置所有人的大转盘抽奖机会为1
  * */
    public void recover() {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set sieve_chance=5,big_turn_chance = 1");
    }

    /*把今天未签到打卡的人的签到次数直接清空*/
    public void emptied() {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set sign_num=0 where status=0");
    }

    public void udateSign() {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set status=0");

    }

    /*当用户中奖以后通过session中的openid去数据库中查询游戏表中的id*/
    public ActGame findActId(String openid) {
        ActGame actGame = gameDao.findFirst("SELECT * from " + ActGame.TABLE_NAME + " WHERE act_user_id=(select id from " + ActUser.TABLE_NAME + " where wechat_openid=?)", openid);
        return actGame;
    }

    /*依据游戏类别查询用户大转盘机会*/
    public ActGame bigChance(Long userid) {
        ActGame ag = gameDao.findFirst("select ag.big_turn_chance from " + ActGame.TABLE_NAME + "  ag where act_user_id=?", userid);
        return ag;
    }

    /*依据游戏类别查询对应的奖品集合  1：大转盘*/
    public List<ActPrize> typePrize(int typeid) {
        return prizeDao.find("select * from " + ActPrize.TABLE_NAME + "  ap where type=?", typeid);
    }

    /*减少用户大转盘机会一次*/
    public int lessOneBig(Long userid) {
        return gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set big_turn_chance=(big_turn_chance-1) where act_user_id=?", userid);
    }

    /*添加用户大转盘机会一次*/
    public int addOneBig(Long userid) {
        return gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set big_turn_chance=(big_turn_chance+1) where act_user_id=?", userid);
    }

    /*减少奖品数量一个*/
    public int lessOnePrize(Long prizeid) {
        return gameDao.getDb().update("update " + ActPrize.TABLE_NAME + " set still_num=(still_num-1)  where id=?", prizeid);
    }

    /*查询奖品剩余数量*/
    public int stillNum(Long prizeid) {
        int num = gameDao.getDb().queryInt("select still_num from " + ActPrize.TABLE_NAME + " where id=?", prizeid);
        return num;
    }

    /*查询奖品总数剩余数量*/
    public int allNum(Long prizeid) {
        int num = gameDao.getDb().queryInt("select all_num from " + ActPrize.TABLE_NAME + " where id=?", prizeid);
        return num;
    }

    /*根据openid查询用户的奖品,个人中心页面*/
    public List<ActGamePrize> myPrize(String openid) {
        return priGameDao.find("SELECT *,DATE_FORMAT(agprize.accept_time, '%Y-%m-%d ') time  from " + ActUser.TABLE_NAME + "  auser LEFT JOIN " + ActGame.TABLE_NAME + " agame " +
                "ON auser.id=agame.act_user_id LEFT JOIN " + ActGamePrize.TABLE_NAME + " agprize ON agame.id=agprize.game_id " +
                "LEFT JOIN " + ActPrize.TABLE_NAME + " aprize ON agprize.prize_id=aprize.id WHERE wechat_openid=? AND prize_id NOT in(1,2,3,4,5)" , openid);
    }

    /*主页查询多少人参与活动*/
    public ActUser findnum() {
        return dao.findFirst("select count(id) num from " + ActUser.TABLE_NAME);
    }

    /*查询用户的签到次数,后来一直需要游戏表，修改为全查*/
    public ActGame findSignIn(String openid) {
        ActGame actGame = gameDao.findFirst("select * from " + ActGame.TABLE_NAME + " where act_user_id=(select id from " + ActUser.TABLE_NAME + " where wechat_openid=?)", openid);
        return actGame;
    }

    /*判断签到打卡是否为null*/
    public boolean isSign(String openid) {
        boolean result = false;
        ActGame actGame = gameDao.findFirst("select sign_num from " + ActGame.TABLE_NAME + " where act_user_id=(SELECT id from " + ActUser.TABLE_NAME + " where wechat_openid=?)", openid);
        if (actGame.getSignNum() == null) {
            result = false;
        } else {
            result = true;
        }
        return result;
    }

    /*根据openid把签到次数加一*/
    /*添加用户大转盘机会一次*/
    public int addOneSign(String openid) {
        return gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set sign_num=(sign_num+1) where act_user_id=(SELECT id from " + ActUser.TABLE_NAME + " where wechat_openid=?)", openid);
    }


    /*中奖编号获取方法：实现原理查询中奖编号最后一条记录进行拼接相加后得到当天的奖品流水编号,*/
    public String lastPrizeNo() {
        ActGamePrize agp = priGameDao.findFirst("select agp.prize_num  from " + ActGamePrize.TABLE_NAME + " agp order by id desc limit 1");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); // 时间字符串产生方式
        StringBuffer newNo = new StringBuffer();
        newNo.append("NO" + format.format(new Date()));
        if (agp.getPrizeNum() == null) {//第一条记录不存在
            newNo.append("0001");
        } else {
            int oldNo = Integer.valueOf(agp.getPrizeNum().substring(10));
            if (oldNo < 9) {
                newNo.append("000" + (oldNo + 1));
            } else {
                if (oldNo == 9) {
                    newNo.append("0010");
                } else {
                    if (99 > oldNo && oldNo > 9) {
                        newNo.append("00" + (oldNo + 1));
                    } else {
                        if (oldNo == 99) {
                            newNo.append("0100");
                        } else {
                            if (999 > oldNo && oldNo > 99) {
                                newNo.append("0" + (oldNo + 1));
                            } else {
                                if (oldNo == 999) {
                                    newNo.append("1000");
                                } else {
                                    if (oldNo > 999) {
                                        newNo.append(oldNo + 1);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return newNo.toString();
    }

    /**
     * 抽奖方法
     *
     * @param apize
     * @return
     */
    public ActPrize isPrize(List<ActPrize> apize) {

        Integer totalPri = 0;//总的中奖区间
        List<Integer> priz = new ArrayList<>();//存储每个奖品
        priz.add(0);
        //遍历每个奖品剩余数量，放置集合中
        if (apize != null) {
            for (ActPrize ap : apize) {
                totalPri += ap.getStillNum();
                priz.add(totalPri);
            }
        }
        if (totalPri != 0) {
            //获取总的一个随机数
            int randomPri = new Random().nextInt(totalPri);
            //判断取到的随机数在哪个两个奖品的数量区间中即为中奖
            for (int i = 0, size = priz.size(); i < size; i++) {
                if (randomPri >= priz.get(i) && randomPri < priz.get(i + 1)) {
                    return apize.get(i);
                }
            }
        }
        return null;
    }


    @Override
    public void clearCache() {
    }

    @Override
    public void removeCache(Object... objects) {
    }

    @Override
    public ActUser get(Object... objects) {
        return null;
    }

    public void updateRedNumber(Long userId) {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set red_number=(red_number+1) where act_user_id=?", userId);
    }

    public void updateRed() {
        gameDao.getDb().update("update " + ActGame.TABLE_NAME + " set red_number=0,red_status=0 where act_user_id=?");

    }
}
